﻿
using SIG.Basic.Extensions;
using SIG.Infrastructure.Cache;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Logging;
using SIG.Model.Articles;
using SIG.Repository;
using SIG.Resources.Admin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

namespace SIG.Service
{
    public class ArticleService : EntityService<Article>, IArticleService
    {

        private readonly IArticleRepository _articleRepository;
        private readonly ILoggingService _loggingService;
        private readonly ICacheService _cacheService;

        public ArticleService(IArticleRepository articleRepository, ILoggingService loggingService, ICacheService cacheService)
            : base(articleRepository, cacheService, loggingService)
        {

            _articleRepository = articleRepository;
            _loggingService = loggingService;
            _cacheService = cacheService;
        }

        public async Task<IList<Article>> GetActiveElementsAync(CancellationToken cancellationToken = default(CancellationToken))
        {
            //get list
            var key = $"{EntityNames.Article}_List_Active";

            IList<Article> articlelist;
            if (SettingsManager.Article.EnableCaching)
            {
                if (_cacheService.IsSet(key))
                {
                    articlelist = (IList<Article>)_cacheService.Get(key);

                }
                else
                {
                    var article = await _articleRepository.GetFilteredElementsAsync(m => m.Active, cancellationToken, g => g.Category);
                    articlelist = article.ToList();
                    _cacheService.Set(key, articlelist, SettingsManager.Article.CacheDuration);
                }
            }
            else
            {
                var articles = await _articleRepository.GetFilteredElementsAsync(m => m.Active, cancellationToken, g => g.Category);
                articlelist = articles.ToList();
            }

            return articlelist;

        }



        public Article GetArticleDetail(int id)
        {
            return _articleRepository.GetFirstOrDefault(m => m.Id == id, m => m.Category);
        }

        public List<Article> GetPagedActiveElements(int pageIndex, int pageSize, string keyword, int? categoryId, out int totalCount)
        {

            //get list count
            var keyCount = $"{EntityNames.Article}_ListCount_Active_{keyword}_{categoryId}";

            var totalIQuery = _articleRepository.GetAllElements().Where(g => g.Active);
            if (!string.IsNullOrEmpty(keyword))
                totalIQuery = totalIQuery.Where(g => g.Title.Contains(keyword));
            if (categoryId > 0)
                totalIQuery = totalIQuery.Where(g => g.CategoryId == categoryId);

            if (SettingsManager.Article.EnableCaching)
            {
                if (_cacheService.IsSet(keyCount))
                {
                    totalCount = (int)_cacheService.Get(keyCount);
                }
                else
                {
                    totalCount = totalIQuery.Count();
                    _cacheService.Set(keyCount, totalCount, SettingsManager.Article.CacheDuration);
                }
            }
            else
            {
                totalCount = totalIQuery.Count();
            }


            //get list
            var key = $"{EntityNames.Article}_List_Active_{pageIndex}_{pageSize}_{keyword}_{categoryId}";

            List<Article> article;
            Expression<Func<Article, bool>> filter = g => g.Active;
            Expression<Func<Article, bool>> filterByKeyword = g => g.Title.Contains(keyword);
            Expression<Func<Article, bool>> filterByCategory = g => g.CategoryId == categoryId;

            if (!string.IsNullOrEmpty(keyword))
                filter = filter.AndAlso(filterByKeyword);
            if (categoryId > 0)
                filter = filter.AndAlso(filterByCategory);


            if (SettingsManager.Article.EnableCaching)
            {
                if (_cacheService.IsSet(key))
                {
                    article = (List<Article>)_cacheService.Get(key);

                }
                else
                {
                    article = _articleRepository.GetPagedElements(pageIndex, pageSize, (c => c.CreatedDate), filter, false, g => g.Category).ToList();
                    _cacheService.Set(key, article, SettingsManager.Article.CacheDuration);
                }
            }
            else
            {
                article = _articleRepository.GetPagedElements(pageIndex, pageSize, (c => c.CreatedDate), filter, false, g => g.Category).ToList();
            }

            return article;

        }





   



        public List<Article> GetPagedElements(int pageIndex, int pageSize, string keyword, int? categoryId, out int totalCount)
        {

            //get list count
            var keyCount = $"{EntityNames.Article}_ListCount_{keyword}_{categoryId}";

            var totalIQuery = _articleRepository.GetAllElements();
            if (!string.IsNullOrEmpty(keyword))
                totalIQuery = totalIQuery.Where(g => g.Title.Contains(keyword));
            if (categoryId > 0)
                totalIQuery = totalIQuery.Where(g => g.CategoryId == categoryId);

            if (SettingsManager.Article.EnableCaching)
            {
                if (_cacheService.IsSet(keyCount))
                {
                    totalCount = (int)_cacheService.Get(keyCount);
                }
                else
                {
                    totalCount = totalIQuery.Count();
                    _cacheService.Set(keyCount, totalCount, SettingsManager.Article.CacheDuration);
                }
            }
            else
            {
                totalCount = totalIQuery.Count();
            }


            //get list
            var key = $"{EntityNames.Article}_List_{pageIndex}_{pageSize}_{keyword}_{categoryId}";

            List<Article> articles;
            Expression<Func<Article, bool>> filter = g => true;
            Expression<Func<Article, bool>> filterByKeyword = g => g.Title.Contains(keyword);
            Expression<Func<Article, bool>> filterByCategory = g => g.CategoryId == categoryId;

            if (!string.IsNullOrEmpty(keyword))
                filter = filter.AndAlso(filterByKeyword);
            if (categoryId > 0)
                filter = filter.AndAlso(filterByCategory);


            if (SettingsManager.Article.EnableCaching)
            {
                if (_cacheService.IsSet(key))
                {
                    articles = (List<Article>)_cacheService.Get(key);
                }
                else
                {
                    articles = _articleRepository.GetPagedElements(pageIndex, pageSize, (c => c.CreatedDate), filter, false, g => g.Category).ToList();
                    _cacheService.Set(key, articles, SettingsManager.Article.CacheDuration);
                }
            }
            else
            {
                articles = _articleRepository.GetPagedElements(pageIndex, pageSize, (c => c.CreatedDate), filter, false, g => g.Category).ToList();
            }

            return articles;

        }



        public IEnumerable<Article> RecommendArticles(int count)
        {
            var key = $"{EntityNames.Article}s_Recommend";

            if (!SettingsManager.Article.EnableCaching)
            {
                return _articleRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active && p.Recommend, false).ToList();
            }

            if (_cacheService.IsSet(key))
            {
                return (List<Article>)_cacheService.Get(key);

            }

            var articleList = _articleRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active && p.Recommend, false).ToList();
            _cacheService.Set(key, articleList, SettingsManager.Article.CacheDuration);


            return articleList;
        }
        public IEnumerable<Article> LatesterArticles(int count)
        {
            var key = $"{EntityNames.Article}s_Latester_{count}";

            if (!SettingsManager.Article.EnableCaching)
            {
                return _articleRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active, false).ToList();
            }

            if (_cacheService.IsSet(key))
            {
                return (List<Article>)_cacheService.Get(key);

            }

            var articleList = _articleRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active, false).ToList();
            _cacheService.Set(key, articleList, SettingsManager.Article.CacheDuration);


            return articleList;
        }
        public IEnumerable<Article> LatesterArticles(int count, int categoryId)
        {
            if (categoryId == 0)
                return LatesterArticles(count);

            var key = $"{EntityNames.Article}s_Latester_{count}_{categoryId}";
            if (!SettingsManager.Article.EnableCaching)
            {
                return _articleRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active & p.CategoryId == categoryId, false).ToList();
            }

            if (_cacheService.IsSet(key))
            {
                return (List<Article>)_cacheService.Get(key);

            }

            var articleList = _articleRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active & p.CategoryId == categoryId, false).ToList();
            _cacheService.Set(key, articleList, SettingsManager.Article.CacheDuration);


            return articleList;
        }


    }
}
